package com.occludens.admin.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.annotation.Subclass;

@Subclass(index=true)
@Cache
public class Menu extends AdminObjectUI {
	@Index private String link;
	@Load private List<Ref<Object>> items = new ArrayList<Ref<Object>>();
	
	protected Menu() {} // Mandatory for Objectify
	
	public Menu(String name) {
		super(name);
	}
	
	public static Menu getMenu(String name) {
		return ObjectifyService.ofy().load().type(Menu.class).filter("name", name).first().now();
	}
	
	public String getLink() {
		return this.link;
	}
	
	public void setLink(String link) {
		this.link = link;
	}
	
	public List<Object> getItems() {
	    List<Object> returnList = new ArrayList<Object>();
	    Iterator<Ref<Object>> itemsItr = this.items.iterator();
	    while (itemsItr.hasNext()) {
	    	returnList.add(itemsItr.next().get());
	    }//End of while itemsItr
	    return returnList;
	}

	public void setItems(List<Object> items) {
		Iterator<Object> itemsItr = items.iterator();
	    while (itemsItr.hasNext()) {
	    	Object item = itemsItr.next();
	    	if (item.getClass().equals(Command.class) || item.getClass().equals(Menu.class)) {
	    		Ref<Object> itemRef = Ref.create((Object)item);
	    		if (!this.items.contains(itemRef)) {
	    			this.items.add(itemRef);
	    		}
	    	}
	    }//End of while itemsItr
	}
	
	public void addItems(Object... items) {
		for (int i=0; i<items.length; i++) {
			Object item = items[i];
			if (item.getClass().equals(Command.class) || item.getClass().equals(Menu.class)) {
	    		Ref<Object> itemRef = Ref.create((Object)item);
	    		if (!this.items.contains(itemRef)) {
	    			this.items.add(itemRef);
	    		}
	    	}
		}
	}
	
	public void removeItems(Object... items) {
		for (int i=0; i<items.length; i++) {
			Object item = items[i];
			if (item.getClass().equals(Command.class) || item.getClass().equals(Menu.class)) {
	    		Ref<Object> itemRef = Ref.create((Object)item);
	    		if (this.items.contains(itemRef)) {
	    			this.items.remove(itemRef);
	    		}
	    	}
		}
	}

}
